package cn.admin.configcenter.configservice.service;

import cn.admin.config.common.Revision;
import cn.admin.configcenter.configservice.domain.ConfigInfo;
import cn.admin.configcenter.configservice.persist.ConfigBaseDAO;
import cn.admin.configcenter.registry.common.info.RevisedData;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Service;

@Service
@Scope("singleton")
public class MannulUpdatedDataService implements InitializingBean {

	@Autowired
	private ConfigService configService;

	@Autowired
	private ConfigBaseDAO configPersistenceDao;

	private static MannulUpdatedDataService instance;

	public static MannulUpdatedDataService getInstance() {
		return instance;
	}

	@Override
	public void afterPropertiesSet() {
		instance = this;
	}

	public String getDataOrCreate(ConfigInfo config,boolean isMannualUpdated) {
		String resultContent = null;
		String configInfoFromDiamond = configService.getConfigByDataIdAndGroupAndSrcIp(
				config.getDataId(),config.getGroup(),config.getSrcIp());
		if (configInfoFromDiamond != null && isMannualUpdated) {
			resultContent = configInfoFromDiamond;
		} else if (configInfoFromDiamond == null) {
			configPersistenceDao.createConfig(config);
		} else if (!isMannualUpdated) {
			configPersistenceDao.silentUpdateConfig(config);
		}
		return resultContent;
	}

	public RevisedData getDataByDataIdAndGroup(String dataId, String group, Revision newRev) {
		String data = configService.getConfig(dataId,group);
		return new RevisedData(data,newRev);
	}

}
